package com.example.demo.util;

import com.alibaba.fastjson.JSONArray;
import com.example.demo.po.TemplateData;
import com.example.demo.po.WxMssVo;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Document;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.util.*;


public class WxUtil {


    public  static String appId ="wx0433b7474fdfe2d4";

    public static String mch_id ="1593381451";

    public  static String appsecret ="22425437072c294178e4edeca2cabb23";

    private static String tokenUrl ="https://api.weixin.qq.com/cgi-bin/token";

    public static final String FIELD_SIGN = "sign";

    public static String key = "v07c6Nact1xhTE27RBb4wM5yAAqoL1yQ";

    public static  String sengUrl ="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?";

//    private static final String wxfilepath ="D:\\wxpay\\apiclient_cert.p12";

    private static final String wxfilepath ="/opt/wxzs/cert/apiclient_cert.p12";

    public static String getToken(){
        StringBuffer  urls = new StringBuffer();
        System.out.println(tokenUrl);
        urls.append(tokenUrl).append("?grant_type=client_credential&appid=").append(appId).append("&secret=").append(appsecret);
        System.out.println(urls.toString());
        String results = HttpClientUtil.doGet(urls.toString());
        com.alibaba.fastjson.JSONObject parseObject = JSONArray.parseObject(results);
        String token = (String) parseObject.get("access_token");
        return token;
    }

    /**
     * 微信统一下单接口,获取预支付标示prepay_id
     * @param out_trade_no 商户订单号
     * @param total_fee 订单金额(单位:分)
     * @param openid 网页授权取到的openid
     * @param spbill_create_ip 用户端ip
     * @param body  货品名称
     * @return
     */
    public static String getPrepayid(String out_trade_no,String total_fee,String openid,String spbill_create_ip,String body){
//        String url1 = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appsecret+"&js_code="+openid+"&grant_type=authorization_code&connect_redirect=1";
//        System.out.println("请求获取openid"+url1);
//        JSONObject jsonObj = loadGetJSON(url1);
//        System.out.println("请求获取openid返回"+jsonObj);
//        if(!jsonObj.containsKey("openid")){
//            return null;
//        }
//        openid = (String) jsonObj.get("openid");
        String result = "";
        String trade_type = "JSAPI";

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("appid", appId);
        map.put("mch_id", mch_id);
        map.put("attach", "【鼎瀚艺术】消费");//附加内容
        map.put("nonce_str", "bxLdikRXVbTP1dHS");
        map.put("body", body);
        map.put("out_trade_no", out_trade_no);
        map.put("total_fee", total_fee);
        map.put("spbill_create_ip", spbill_create_ip);
        map.put("trade_type", trade_type);
        map.put("notify_url", "https://www.51artone.cn/wxInterface/resultofPayForXcx");
        map.put("openid", openid);
        System.out.println(map.toString());
        String content = "";
        try {
            content = generateSignedXml(map,key);
            String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            String jsonObject=loadPostJSON1(url , content,"");//返回的的结果

            if (jsonObject.indexOf("FAIL") != -1) {
//				return null;
            }
            Map<String, String> map1 = new HashMap<String, String>();
            map1 = xmlToMap(jsonObject);
            String prepay_id = (String) map1.get("prepay_id");
            Map<String, String> map2 = new HashMap<String, String>();
            map2.put("appId", appId);
            map2.put("nonceStr", "bxLdikRXVbTP1dHS");
            map2.put("package", "prepay_id="+prepay_id);
            map2.put("signType", "MD5");
            map2.put("timeStamp", (long)((new Date()).getTime()/1000)+"");

            String sign = generateSignature(map2, key);
//
//            return result+="prepay_id:"+prepay_id+",nonce_str:bxLdikRXVbTP1dHS,sign:"+sign +",timeStamp:"+map2.get("timeStamp");
            Map<String, String> map3 = new HashMap<String, String>();
            map3.put("prepay_id",prepay_id);
            map3.put("nonce_str","bxLdikRXVbTP1dHS");
            map3.put("sign",sign);
            map3.put("timeStamp",map2.get("timeStamp"));
            JSONArray jArray = new JSONArray();
            jArray.add(map3);
            return jArray.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 微信申请退款请求
     * @param out_trade_no 商户订单号
     * @param total_fee 订单金额(单位:分)
     * @param transaction_id  微信订单号
     * @return
     */
    public static boolean returnMoney(String transaction_id,String out_trade_no,String total_fee){
        boolean result = false;
        try {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("appid",appId);
            map.put("mch_id", mch_id);
            map.put("nonce_str", "bxLdikRXVbTP1dHS");//随机字符串
            map.put("out_trade_no", out_trade_no);//订单号
            map.put("out_refund_no", out_trade_no);//退款单号
            map.put("total_fee", total_fee);  //订单金额
            map.put("refund_fee", total_fee);  //退款金额
            map.put("refund_desc", "保证金退款");  //退款原因
            map.put("sign_type", "MD5");  //签名类型
            map.put("refund_fee_type", "CNY");  //退款货币种类
            map.put("refund_account", "REFUND_SOURCE_RECHARGE_FUNDS");  //退款资金来源
            System.out.println("签名之前:======="+map.toString());
            String content = "";
            content = generateSignedXml(map,key);
            String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";//退款接口连接
            String jsonObject=loadPostJSON1(url , content, wxfilepath);//返回的的结果
            System.out.println(jsonObject);
            if (jsonObject.indexOf("FAIL") != -1) {
                result = false;
            }else{
                result = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }
        return result;
    }


    /**
     * 处理与微信的get接口
     *
     * @param url
     * @return
     */
    public static JSONObject loadGetJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    yc.getInputStream(), "utf-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null)
                json.append(inputLine);

            in.close();
        } catch (java.net.MalformedURLException oracle) {
        } catch (java.io.IOException oracle) {
        }
        if (StringUtil.isNotBlank(json.toString()))
            return JSONObject.fromObject(json.toString());
        else
            return new JSONObject();
    }


    /**
     * 处理与微信的post接口(JSAPI支付)
     * @param url 请求地址
     * @param json 请求参数
     * @param path 证书地址
     * @return
     * @throws Exception
     */
    public static String loadPostJSON1(String url, String json,String path) throws Exception {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringBuilder jsono = new StringBuilder();
        if(!"".equals(path)){
            // 证书密码，默认为商户ID
            String key = "1593381451";
            // 指定读取证书格式为PKCS12
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            // 读取本机存放的PKCS12证书文件
            FileInputStream instream = new FileInputStream(new File(path));
            try {
                // 指定PKCS12的密码(商户ID)
                keyStore.load(instream, key.toCharArray());
            } finally {
                instream.close();
            }
            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, key.toCharArray()).build();
            SSLConnectionSocketFactory sslsf =
                    new SSLConnectionSocketFactory(sslcontext, new String[] {"TLSv1"}, null,
                            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        }
        HttpEntity s = new StringEntity(json, "UTF-8");
        post.setEntity(s);

        HttpResponse res = client.execute(post);

        HttpEntity entity = res.getEntity();
        EntityUtils.getContentCharSet(entity);
        BufferedReader in = new BufferedReader(new InputStreamReader(
                entity.getContent()));
        String inputLine = null;
        while ((inputLine = in.readLine()) != null) {
            jsono.append(inputLine);
        }
        if (StringUtil.isNotBlank(jsono.toString()))
            return (jsono.toString());
        else
            return "";
    }


    /**
     * 生成带有 sign 的 XML 格式字符串
     *
     * @param data
     *            Map类型数据
     * @param key
     *            API密钥
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data,
                                           String key) throws Exception {
        String sign = generateSignature(data, key);
        data.put(FIELD_SIGN, sign);
        return mapToXml(data);
    }

    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data
     *            待签名数据
     * @param key
     *            API密钥
     *            签名方式
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data,
                                           String key) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        String str = "";
        if(!"".equals(key)){
            sb.append("key=").append(key);
            str = sb.toString();
        }else{
            str = sb.substring(0, (sb.length()-1));
        }
        System.out.println(str);
        return MD5(str).toUpperCase();
    }

    /**
     * 生成 MD5
     *
     * @param data
     *            待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        java.security.MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100)
                    .substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * XML格式字符串转换为Map
     *
     * @param strXML XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> xmlToMap(String strXML) throws Exception {

        Map<String, String> parseStr=new HashMap<String, String>();
        try {
            org.dom4j.Document doc= DocumentHelper.parseText(strXML);
            Element roots=doc.getRootElement();
            //只有根节点……
            Iterator elements=roots.elementIterator();
            while (elements.hasNext()){
                Element child= (Element) elements.next();
                parseStr.put(child.getName(), child.getText());
                List subElemets=child.elements();
                for(int i=0;i<subElemets.size();i++){
                    Element subChild= (Element) subElemets.get(i);
                    parseStr.put(child.getName(), child.getText());
                }

            }
            return parseStr;
        } catch (DocumentException e) {
            e.printStackTrace();
            return parseStr;
        }
    }


    /**
     * 将Map转换为XML格式的字符串
     * @param data
     *            Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<String, String> data) throws Exception {
        org.w3c.dom.Document document = newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key : data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); // .replaceAll("\n|\r",
        // "");
        try {
            writer.close();
        } catch (Exception ex) {
        }
        return output;
    }

    public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//	        documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
//	        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
//	        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
//	        documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
//	        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
//	        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);

        return documentBuilderFactory.newDocumentBuilder();
    }

    public static Document newDocument() throws ParserConfigurationException {
        return newDocumentBuilder().newDocument();
    }

    /**
     * 解密工具直接放进去即可
     */
    public static String decryptS5(String sSrc, String encodingFormat, String sKey, String ivParameter) throws Exception {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] raw = decoder.decodeBuffer(sKey);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(decoder.decodeBuffer(ivParameter));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] myendicod = decoder.decodeBuffer(sSrc);
            byte[] original = cipher.doFinal(myendicod);
            String originalString = new String(original, encodingFormat);
            JSONObject jsonobject = JSONObject.fromObject(originalString);
            return jsonobject.get("phoneNumber").toString();
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 订阅推送
     * @return
     */
    public static boolean templateMessage(String openid,String formId,
                                          String templateId,Map<String, TemplateData> m){
        try{
        //先获取TOKEN
        String token = WxUtil.getToken();
            String url = sengUrl +
                    "access_token=" + token;

            HttpHeaders headers =new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            JSONObject param = new JSONObject();
            param.put("touser", openid);
            param.put("template_id",templateId);
            param.put("form_id", formId);
            param.put("data", m);

            org.springframework.http.HttpEntity<String> formEntity = new  org.springframework.http.HttpEntity(param, headers);
            RestTemplate restTemplate =new RestTemplate();
            ResponseEntity<String> responseEntity =
                    restTemplate.postForEntity(url, formEntity, String.class);

            String results = responseEntity.getBody();
            System.out.println("短信发送结果********"+results);
            com.alibaba.fastjson.JSONObject parseObject = JSONArray.parseObject(results);
            Integer errcode = (Integer) parseObject.get("errcode");
            String errmsg =(String) parseObject.get("errmsg");
            if(errcode==0||errmsg=="ok")
                return true;
            else
                return false;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 按照类型发生消息
     * @param openid
     * @param type
     * @param map
     * @return
     */
    public static boolean sendType(String openid,String type,
                                   Map<String, String> map){
        Map<String, TemplateData> m =new HashMap<String, TemplateData>();
        TemplateData keyword1 = new TemplateData();
        TemplateData keyword2 = new TemplateData();
        TemplateData keyword3 = new TemplateData();
        TemplateData keyword4 = new TemplateData();
        keyword1.setValue(map.get("key1"));
        keyword2.setValue(map.get("key2"));
        keyword3.setValue(map.get("key3"));
        keyword4.setValue(map.get("key4"));
        m.put("keyword1", keyword1);
        m.put("keyword2", keyword2);
        m.put("keyword3", keyword3);
        m.put("keyword4", keyword4);
        String templateId = null;
        //下单成功通知1 新报价通知2 退款结果通知3 订单发货提醒4 预约活动通知5
        if("1".equals(type.trim())){
            templateId="FcG8qk1RP2ga7ZNiX7nWAUmKmsFx-JttjAwJX8eY15Q";
        }else if("2".equals(type.trim())){
            templateId="cvzuhqgQlX4K8SyGQ_MgmLlBt6tg-gb9paVupm3VoNs";
        }else if("3".equals(type.trim())){
            templateId="IlImR6XU2ZM2YE551cyQVU6xsUeJN7U1siaJqGibhYw";
        }else if ("5".equals(type.trim())) {
            templateId="qIhkIEH14P7YOT4l_xq_hNm4HR9jxYoz3LtTut7qX0M";
        }
        else{
            templateId="RUqzFpcwv4Y2oArqOW4OnuuZWD2YiAing1e7Djhky2I";
        }
        if(WxUtil.templateMessage(openid,"1546",templateId,m))
            return true;
        else
            return false;
    }

    public static void main(String[] args) throws Exception {
//        String data = WxUtil.getPrepayid("OA123456", (int)(Double.parseDouble("0.01")*100)+"", "oTOsd5MBspVIh7XBRoSBXdGmnrGQ", "123.12.12.123", "【壹艺术】支付");
//        System.out.println(data);

//        String resultMessage = WxUtil.decryptS5("2YMEHOfEgpRXSNFabmf5TMCZx1/wmM9Dy6/cD64VG7mKIM0iJCYN1nLh/YdeGTWQ+Wtvntlt6mC/sveJ14hdgoveobB02DY8S373se21rpMSZwI2NUn5ex/tsvEQxfohMFqWzm+lrOIhohd5QRQprDh0lH7ay6vsn+hYeD0x1IMwoFr0CAI2pBlyMI6vfYdSAn4NzzVDNC6HISz8wwsfSg==",
//                "UTF-8","m3vdICjJQYy0JYWCgvqNWw==","8xzX5imDdi1jiEpzAbmQSA==");
//        System.out.println(resultMessage);
//        WxUtil wx = new WxUtil();
        Map<String, TemplateData> m =new HashMap<String, TemplateData>();
        TemplateData keyword1 = new TemplateData();
        keyword1.setValue("订单号");
        m.put("keyword1", keyword1);
        TemplateData keyword2 = new TemplateData();
        keyword2.setValue("商品名称");
        m.put("keyword2", keyword2);

        TemplateData keyword3 = new TemplateData();
        keyword3.setValue("订单金额");
        m.put("keyword3", keyword3);

        TemplateData keyword4 = new TemplateData();
        keyword4.setValue("备注");
        m.put("keyword4", keyword4);
        WxUtil.templateMessage("oTOsd5MBspVIh7XBRoSBXdGmnrGQ","1546","IlImR6XU2ZM2YE551cyQVU6xsUeJN7U1siaJqGibhYw",m);
//        boolean a =WxUtil.returnMoney("4200000527202005283757009896","O20052817081795010006","1");
//        System.out.println(WxUtil.getToken());
    }


}
